import { useRef } from 'react'
import { IModalComponentRef } from '@/components/page-modal'
import { FormInstance } from 'antd'
import { IGetCode } from '@/global/type'
import { VerifyType } from '@/global/constant'

interface IConfig {
  okCb?: (form: FormInstance | undefined) => void
  cancelCb?: (form: FormInstance | undefined) => void
  afterCloseResetStatusCb?: () => void
}

function usePageModal({ okCb, cancelCb, afterCloseResetStatusCb }: IConfig) {
  // 获取modal的实例
  const pageModalRef = useRef<IModalComponentRef>(null)

  function onModalOk(form: FormInstance | undefined) {
    form
      ?.validateFields()
      .then(async () => {
        // 每个modal框传入的函数执行不一样的操作
        await okCb?.(form)
        // 关闭弹框
        pageModalRef.current?.closeModal()
        // 外面传进来一个回调，这个操作将在弹框关闭后执行
        afterCloseResetStatusCb?.()
        // 清除表单以及重置表单在这里做好操作了，不用在外边再做
        form?.resetFields()
      })
      .catch((error) => {
        console.log(error)
      })
  }

  // modal的取消事件
  function onModalCancel(form: FormInstance | undefined) {
    cancelCb?.(form)
    pageModalRef.current?.closeModal()
    form?.resetFields()
  }

  // 获取二次认证的验证码
  function getCodeClick() {
    // 以下参数是二次认证的，暂时不知道后面会不会变
    const form = pageModalRef.current?.getFormInstance()
    const { type, email, userPhone } = form && form.getFieldsValue()
    const config: IGetCode = {
      type,
      data: type === VerifyType.Phone ? userPhone : email
    }
    return config
  }

  return { pageModalRef, onModalOk, onModalCancel, getCodeClick }
}

export default usePageModal
